//
//  BudgetManagerView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 12.04.25.
//

import SwiftUI

struct BudgetManagerView: View {
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.presentToast) var presentToast
    @StateObject var viewModel = BudgetManagerViewModel()
    @State var showBudgetTotalSetDialog = false
    @State var showBudgetCategorySetDialog = false
    @State var categorySetType: BudgetCategorySetType = .categorySelect
    @State var selectedCategory: AccountingCategory? = nil
    @State var selectedBudget: AccountingBudget? = nil
    
    var forAdd = false
    
    var body: some View {
        VStack {
            BudgetManagerHeaderView(
                budgetTotalAmount: $viewModel.budgetTotalAmount,
                expenseAmount: $viewModel.expenseAmount,
                surplusAmount: $viewModel.surplusAmount,
                onSetBudgetClick: {
                    // 设置月预算
                    showBudgetTotalSetDialog = true
                }
            )
            .padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
            
            HStack (spacing: 0) {
                Text("分类预算")
                    .font(.system(size: 14))
                    .foregroundColor(Color.koiColorTitleSecond)
                Spacer()
                Button(action: {
                    showBudgetCategorySetDialog = true
                    categorySetType = .categorySelect
                }) {
                    HStack {
                        Image("koi_ic_add")
                            .resizable()
                            .frame(width: 13, height: 13)
                        Text("添加分类预算")
                            .font(.system(size: 13))
                            .foregroundColor(Color.koiColorTitle)
                    }
                }
            }
            .padding(EdgeInsets(top: 20, leading: 20, bottom: 0, trailing: 20))
            .sheet(isPresented: $showBudgetCategorySetDialog) {
                switch categorySetType {
                case .categorySelect:
                    CategorySelectGridView(
                        onCategoryClick: { selectedCategory in
                            if selectedCategory.isDisable {
                                // 已经设置过预算
                                presentToast(.init(message: "此类别已经设置过预算"))
                            } else {
                                viewModel.selectedCategory = selectedCategory
                                categorySetType = .amountSet(nil)
                                showBudgetCategorySetDialog = true
                            }
                        },
                        disableCategoryList: viewModel.getBudgetCategoryList()
                    )
                    .presentationDetents([.medium])
                case .amountSet(let selectedBudget):
                    BudgetSetCategoryView(
                        selectedCategory: viewModel.selectedCategory!,
                        selectedBudget: selectedBudget,
                        onDoneClick: { inputAmount in
                            viewModel.saveBudgetCategory(inputAmount: inputAmount)
                        }
                    )
                    .presentationDetents([.medium])
                }
            }
            
            List {
                ForEach(viewModel.budgetList) { item in
                    Button (action: {
                        viewModel.selectedBudget = item.budget
                        viewModel.selectedCategory = item.category
                        categorySetType = .amountSet(item.budget)
                        showBudgetCategorySetDialog = true
                    }) {
                        BudgetManagerItemView(budget: item)
                            .padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 10))
                            .background(Color.koiColorBackgroundItem)
                            .cornerRadius(16)
                            .padding(.vertical, 5)
                    }
                    .listRowSeparator(.hidden)
                    .listRowInsets(EdgeInsets())
                    .listRowBackground(Color.clear)
                }
            }
            .scrollContentBackground(.hidden)
            .overlay(Group {
                if viewModel.budgetList.isEmpty {
                    ZStack {
                        Color.koiColorBackground.ignoresSafeArea()
                    }
                }
            })
            .background(Color.koiColorBackground)
            .listStyle(.plain)
            .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing:20)) // 去除边距
            .ignoresSafeArea(.container, edges: .bottom)
        }
        .koiToolbar(title: Text("月预算").foregroundColor(Color.koiColorTitle))
        .sheet(isPresented: $showBudgetTotalSetDialog) {
            BudgetSetTotalView(
                totalAmount: viewModel.budgetTotalAmount,
                onDoneClick: { inputAmount in
                    // 保存预算
                    viewModel.saveBudgetTotal(inputAmount: inputAmount)
                },
                onDeleteAllClick: {
                    // 删除全部预算
                    viewModel.deleteAllBudget()
                }
            )
            .presentationBackground(Color.koiColorBackground)
            .presentationDetents([.medium])
        }
        .background(Color.koiColorBackground)
        .onChange(of: viewModel.saveTotalBudgetState) { value in
            if value == "" {
                return
            }
            if value == "success" {
                viewModel.saveTotalBudgetState = ""
                showBudgetTotalSetDialog = false
                presentToast(.init(message: "总预算设置成功"))
                loadData()
                KoiEvent.homeReload.send()
            } else {
                let msg = value
                viewModel.saveTotalBudgetState = ""
                presentToast(.init(message: msg))
            }
        }
        .onChange(of: viewModel.saveCategoryBudgetState) { value in
            if value == "" {
                return
            }
            if value == "success" {
                viewModel.saveCategoryBudgetState = ""
                showBudgetCategorySetDialog = false
                presentToast(.init(message: "分类预算设置成功"))
                loadData()
                KoiEvent.homeReload.send()
            } else {
                let msg = value
                viewModel.saveTotalBudgetState = ""
                presentToast(.init(message: msg))
            }
        }
        .onChange(of: viewModel.deleteAllBudgetState) { value in
            if value == "" { return }
            if value == "success" {
                viewModel.deleteAllBudgetState = ""
                showBudgetTotalSetDialog = false
                presentToast(.init(message: "预算已清除"))
                loadData()
                KoiEvent.homeReload.send()
            } else if value == "fail" {
                presentToast(.init(message: "预算清除失败"))
            }
        }
        .onAppear {
            loadData()
            if forAdd {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    showBudgetTotalSetDialog = true
                }
            }
        }
    }
    
    private func loadData() {
        viewModel.loadData()
    }
}

enum BudgetCategorySetType {
    case categorySelect, amountSet(AccountingBudget?)
}

#Preview {
    BudgetManagerView()
}
